package com.example.hlddz2.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.hlddz2.R;
import com.example.hlddz2.repository.CartRepository;
import com.example.hlddz2.repository.OrderRepository;

import java.util.ArrayList;
import java.util.List;

public class CartFragment extends Fragment {

    private CartRepository repository;
    private Adapter adapter;
    private TextView tvTotal;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_cart, container, false);
        RecyclerView rv = root.findViewById(R.id.rv_cart);
        tvTotal = root.findViewById(R.id.tv_total);
        android.widget.Button btnCheckout = root.findViewById(R.id.btn_checkout);
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new Adapter();
        rv.setAdapter(adapter);

        repository = CartRepository.getInstance(requireContext());
        adapter.attachRepository(repository);
        repository.getCart().observe(getViewLifecycleOwner(), items -> {
            adapter.setData(items);
            tvTotal.setText("合计：¥ " + String.format("%.2f", repository.calcTotal()));
        });

        btnCheckout.setOnClickListener(v -> {
            List<CartRepository.CartItem> cartItems = repository.getCart().getValue();
            if (cartItems != null && !cartItems.isEmpty()) {
                // 创建订单
                OrderRepository orderRepo = OrderRepository.getInstance(requireContext());
                orderRepo.createOrderFromCart(cartItems);

                // 清空购物车
                repository.clear();
                Toast.makeText(getContext(), "结算成功，订单已创建", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "购物车为空，无法结算", Toast.LENGTH_SHORT).show();
            }
        });

        return root;
    }

    static class Adapter extends RecyclerView.Adapter<Adapter.VH> {
        private List<CartRepository.CartItem> data = new ArrayList<>();
        void setData(List<CartRepository.CartItem> d) { data = d == null ? new ArrayList<>() : d; notifyDataSetChanged(); }
        private CartRepository repository;

        void attachRepository(CartRepository r) { this.repository = r; }

        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_cart, parent, false);
            return new VH(v);
        }

        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            CartRepository.CartItem it = data.get(position);
            holder.name.setText(it.name);
            holder.price.setText("¥ " + it.price);
            holder.count.setText(String.valueOf(it.count));
            if (it.image != null && !it.image.isEmpty()) {
                Glide.with(holder.itemView.getContext())
                        .load(it.image)
                        .placeholder(R.color.light_gray)
                        .into(holder.image);
            }

            holder.btnPlus.setOnClickListener(v -> {
                if (repository != null) repository.updateCount(it.goodsId, it.count + 1);
            });
            holder.btnMinus.setOnClickListener(v -> {
                if (repository != null) repository.updateCount(it.goodsId, Math.max(1, it.count - 1));
            });
            holder.btnDelete.setOnClickListener(v -> {
                if (repository != null) repository.remove(it.goodsId);
            });
        }

        @Override
        public int getItemCount() { return data == null ? 0 : data.size(); }

        static class VH extends RecyclerView.ViewHolder {
            ImageView image; TextView name; TextView price; TextView count; TextView btnPlus; TextView btnMinus; TextView btnDelete;
            VH(@NonNull View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.iv_image);
                name = itemView.findViewById(R.id.tv_name);
                price = itemView.findViewById(R.id.tv_price);
                count = itemView.findViewById(R.id.tv_count);
                btnPlus = itemView.findViewById(R.id.btn_plus);
                btnMinus = itemView.findViewById(R.id.btn_minus);
                btnDelete = itemView.findViewById(R.id.btn_delete);
            }
        }
    }
}


